<template>
  <a-card>
    <a-spin :spinning="spinning" size="large">
      <Header :title="'返回'" :subTitle="subTitle" :hasBackPath="true" @headerBack="$router.back()"></Header>
      <a-form-model
        ref="rulesForm"
        labelAlign="left"
        :model="form"
        :rules="rules"
        :labelCol="{ lg: { span: 3 }, sm: { span: 4 } }"
        :wrapperCol="{ lg: { span: 14 }, sm: { span: 17 } }"
      >
        <a-form-model-item v-if="type > 1" style="margin-left: 40px;"  :label="type == 2 ? '作废原因' : '延期原因'" prop="reason" :labelCol="{ span: 24 }">
          <a-textarea
            allowClear
            v-model="form.reason"
            placeholder="请说明原因"
          />
        </a-form-model-item>
      <!-- class="hidden-title" -->
        <a-form-model-item label="添加需要延期的优惠券号" style="margin-left: 40px;" :labelCol="{ span: 24 }" required>
          <a-input
            style="width: 40%"
            allowClear
            v-model="nos"
            placeholder="请填写本批次优惠券号"
          />
          <a-button type="primary" style="margin-left: 15px;" @click="handleAddAssociatedCoupon">确认添加</a-button>
<!--          :file-list="fileList" :remove="handleRemove" :before-upload="beforeUpload"-->
          <a-upload
            accept=".csv, application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
            name="操作券"
            :showUploadList="false"
            :multiple="false"
            :data="uploadData"
            :action="uploadUrl"
            @change="handleChange"
          >
            <a-button style="margin-left: 15px;">批量添加</a-button>
          </a-upload>
          <div>当前共成功添加了{{data.length}}个券号，请确保填写信息正确！<span style="text-decoration: underline;color: blue;cursor: pointer" @click="handleExport">点击下载导入模版</span></div>
          <a-table :pagination="pagination"  :columns="type == 3 ? delayColumns : memberColumns" :data-source="data" :rowKey="record => record.id" @change="tableChange" size="middle">
            <span slot="action" slot-scope="text, record">
              <a-popconfirm title="请确认是否删除本条信息？" @confirm="handleDeletAssociatedCoupon(record.id)">
                <a-icon type="delete" style="cursor: pointer;" />
              </a-popconfirm>
            </span>
          </a-table>
          <a-form-model-item class="show-title" v-if="type==3" :labelCol="{lg: { span: 4 }, sm: { span: 5 }}" label="有效期延至" prop="time" >
            <a-date-picker
              v-model="form.time"
              show-time
              type="date"
              valueFormat="YYYYMMDD"
              format="YYYYMMDD"
              placeholder="请选择"
            />
          </a-form-model-item>
        </a-form-model-item>
        <a-divider />
        <a-form-model-item :wrapperCol="{ span: 24 }" style="text-align: center">
          <a-button v-if="type==1" type="primary" @click="handleSubmit">打印</a-button>
          <template v-if="type==2">
            <a-button type="primary" @click="handleSubmit">废除</a-button>
            <div style="color: red;">一旦确认作废，无法撤回，请仔细检查需作废优惠券号！</div>
          </template>
          <template v-if="type==3">
            <a-button type="primary" @click="handleSubmit">保存</a-button>
            <div style="color: red;">一旦确认延期，无法撤回，请仔细检查需延期优惠券号！</div>
          </template>
        </a-form-model-item>
      </a-form-model>
    </a-spin>
  </a-card>
</template>
<script>
import Header from '@/views/box/components/layouts/Header'
import { logAddOne, logPage, voucherDelay, logDelete, logExpert, voucherCancel, printDetails, logTemplateExpert } from '@/api/headquartersCoupon/index'
  const memberColumns = [
    {
      title: '序号',
      width: 1,
      align: 'center',
      customRender: (text,record,index) => `${index+1}`
    },
    {
      title: '优惠券号',
      width: 4,
      align: 'center',
      dataIndex: 'nos'
    },
    {
      title: '操作',
      width: 1,
      align: 'center',
      scopedSlots: { customRender: 'action' }
    }
  ];
  const delayColumns = [
    {
      title: '序号',
      width: 1,
      align: 'center',
      customRender: (text,record,index) => `${index+1}`
    },
    {
      title: '优惠券号',
      width: 4,
      align: 'center',
      dataIndex: 'nos'
    },
    {
      title: '有效期',
      width: 4,
      align: 'center',
      dataIndex: 'validdate'
    },
    {
      title: '操作',
      width: 1,
      align: 'center',
      scopedSlots: { customRender: 'action' }
    }
  ];

  export default {
    components: {
      Header
    },
    data() {
      return {
        type: this.$route.query.type,
        uploadData: {
          token: this.$route.query.token,
          type: this.$route.query.type
        },
        uploadUrl: logExpert,
        exportUrl: logTemplateExpert,
        pagination: {
          current: 1,
          pageSize: 10,
          total: 0,
          showTotal: total => `共有 ${total} 条数据`
        },
        nos: '',
        data:[],
        delayColumns,
        memberColumns,
        spinning: false,
        form: {
          time: '',
          reason: ''
        },
        rules: {
          time: [
            { required: true, message: '请选择', trigger: 'change'}
          ],
          reason: [
            { required: true, message: '请填写', trigger: 'blur' }
          ]
        }
      }
    },
    computed: {
      token() {
        return this.$route.query.token
      },
      subTitle() {
        // 1.补打印 2.作废 3.延期-
        const subTitleList = ['优惠券补打印/快速添加', '添加需作废的优惠券号/快速添加', '优惠券延期/快速添加']
        return subTitleList[this.type - 1]
      }
    },
    watch: {
    },
    activated() {
    },
    created() {
      this.getList()
    },
    mounted() {
    },
    methods: {
      handleAddAssociatedCoupon() {
        var myreg = /^[0-9a-zA-Z\-]*$/g
        if (!myreg.test(this.nos)) {
          this.$message.info('请输入正确的格式！')
          return false
        }
        const data = {
          nos: this.nos,
          token: this.token,
          type: this.type
        }
        logAddOne(data).then(res => {
          if (res.code == 200) {
            this.getList()
          } else {
            this.$message.warning(res.msg || res.message)
          }
        })
      },

      // 列表
      getList() {
        const data = {
          current: this.pagination.current,
          size: this.pagination.pageSize,
          token: this.token,
          type: this.type
        }
        logPage(data).then(res => {
          if (res.code == 200) {
            const { records, total} = res.data
            const pagination = { ...this.pagination }
            pagination.total = total
            this.pagination = pagination
            this.data = records
          } else {
            this.$message.warning(res.msg || res.message)
          }
        })
      },

      tableChange(pagination) {
        const pager = { ...this.pagination }
        pager.current = pagination.current
        this.pagination = pager
        this.getList()
      },

      // 删除
      handleDeletAssociatedCoupon(id) {
        const data = {
          id,
          token: this.token,
          type: this.type
        }
        logDelete(data).then(res => {
          if (res.code == 200) {
           this.getList()
          } else {
            this.$message.warning(res.msg || res.message)
          }
        })
      },

      // 批量添加发放对象
      handleChange(info) {
        if (info.file.status !== 'uploading') {
          console.log(info.file, info.fileList)
        }
        if (info.file.status === 'done') {
          const {msg, message, code, data} = info.file.response
          if (code == 200 ) {
            this.refreshSendUserList()
          } else {
            this.$message.error(msg || message)
          }
          
        } else if (info.file.status === 'error') {
          this.$message.error(`${info.file.name} file upload failed.`)
        }
      },

      refreshSendUserList() {
        this.pagination.current = 1
        this.getList()
      },

      //下载导入模板
      handleExport() {
        window.location.href = this.exportUrl
      },

      handleSubmit() {
        this.$refs.rulesForm.validate(valid => {
          if (valid) {
            const pageId = this.$route.query.pageId
            if (!this.data.length) {
              this.$message.info('请添加券号！')
              return
            }
            const data = {
              ...this.form,
              pageId,
              token: this.token,
              validDate: this.form.time
            }
            this.spinning = true
            // 1.补打印 2.作废 3.延期
            if (this.type == 1) {
              printDetails(data).then(res => {
                this.spinning = false
                if (res.code === 200) {
                  const data = decodeURIComponent(JSON.stringify(res.data))
                  this.$router.push(`/headquarters-coupon/print/1?data=${data}`)
                } else {
                  this.$message.warning(res.msg || res.message)
                }
              }).catch(err => {
                this.spinning = false
              })
              return
            }
            const submitApi = this.type == 2 ? voucherCancel : voucherDelay
            submitApi(data).then(res => {
              this.spinning = false
              if (res.code === 200) {
                this.$router.go(-1)
              } else {
                this.$message.warning(res.msg || res.message)
              }
            }).catch(err => {
              this.spinning = false
            })
          } else {
            console.log('error submit!!');
            return false;
          }
        })
      }
    }
  }
</script>
<style scoped>
  .association-list /deep/td{
    padding-bottom: 0 !important;
  }
  .hidden-title  /deep/.ant-form-item-label > label{
    visibility: hidden;
  }
  .show-title  /deep/.ant-form-item-label > label{
    visibility: visible;
    width: 20%;
  }
</style>
